﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using DBUtil;

namespace LIMS_QueueService
{
    public class QueueService : ServiceBase
    {
        public static Timer timer = new Timer();
        public static double interval = (1000 * 60) * 3; // 5 分钟 间隔执行


        /// <summary>
        /// 如果 间隔执行设定修改，则在下次执行更新间隔时间段
        /// </summary>
        private void RefashInterval()
        {
            ConfigurationManager.RefreshSection("connectionStrings");
            ConfigurationManager.RefreshSection("appSettings");
            interval = Utils.ConvertTo<double>(ConfigurationManager.AppSettings["Interval"], 3);
            timer.Interval = interval * (1000 * 60);
        }

        protected override void OnStart(string[] args)
        {
            RefashInterval();
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
            timer.Start();
            LogUtils.LogInfo("老系统 二维码队列服务开始", Developer.MJ);
        }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            RefashInterval();
            try
            {
                ExecQueue();
            }
            catch (Exception ex)
            {
                LogUtils.LogError("老系统 二维码队列服务异常", Developer.MJ, ex);
            }
        }

        protected override void OnStop()
        {
            LogUtils.LogInfo("老系统 二维码队列服务停止", Developer.MJ);
        }

        protected override void OnShutdown()
        {
            LogUtils.LogInfo("老系统 二维码队列服务关闭", Developer.MJ);
        }

        /// <summary>
        ///SQL Server 待赋值更新 的 htmlContent
        /// </summary>
        public static void ExecQueue()
        {
            DBSession db = new DBSession(DataBaseType.MsSql);
            string select_sql = @"select top 10 srq.*,psn.Product_Id from SendReportQueue srq left join ProductSelectNo psn on psn.SelectNo=srq.SelectNo where [state]=0 order by srq.Id asc";
            DataTable QrCode_Data = db.QueryTable(select_sql, 300);

            if (QrCode_Data != null && QrCode_Data.Rows.Count == 0)
            {
                System.Threading.Thread.Sleep(5000);
            }
            else
            {
                foreach (DataRow dr in QrCode_Data.Rows)
                {
                    string product_Id = dr["Product_Id"].ToString();
                    string selectNo = dr["SelectNo"].ToString();
                    if (string.IsNullOrEmpty(product_Id))
                    {
                        string del_sql = "delete from SendReportQueue where selectno ='" + selectNo + "';";
                        db.ExecuteSql(del_sql);
                        continue;
                    }
                    DateTime addTime = Convert.ToDateTime(dr["AddTime"].ToString());
                    string url = string.Empty;
                    string htmlContent = string.Empty;
                    try
                    {
                        url = BuildRelativeUrl(product_Id, selectNo);
                        htmlContent = BuildHtml(product_Id);

                        //更新状态及保存html内容
                        Hashtable ht = new Hashtable();
                        ht.Add("State", 1);
                        ht.Add("QueueTime", DateTime.Now);
                        ht.Add("url", url);
                        ht.Add("HtmlContent", htmlContent);
                        ht.Add("SelectNo", selectNo);
                        int res = db.Update(ht, "SendReportQueue", "SelectNo");
                        LogUtils.LogInfo("老系统 执行更新", Developer.MJ, selectNo);
                    }
                    catch (Exception ex)
                    {
                        LogUtils.LogInfo("老系统 二维码队列服务出错", Developer.MJ, ex, ex.InnerException);
                    }
                }
            }
        }
        /// <summary>
        /// 生成相对路径
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="selectNo"></param>
        /// <returns></returns>
        public static string BuildRelativeUrl(string productId, string selectNo)
        {
            DBSession db = new DBSession(DataBaseType.MsSql);
            string relativeUrl = string.Empty;
            try
            {
                string type_style_url = string.Empty;
                string select_sql = @"select top 1 ptn.NOID,psn.NOID from Product p
	                left join ProductStyle ps on ps.Id = p.ProductStyle_Id
	                left join ProductType pt on pt.Id=ps.ProductType_Id
	                left join ProductTypeNo ptn on ptn.ProductType_Id=pt.Id
	                left join ProductStyleNo psn on psn.ProductStyle_Id=ps.Id
	                left join TackItems tis on tis.Id=ptn.TackItems_Id
	                left join TackItems tis1 on tis1.Id=psn.TackItems_Id 
	                where tis.AcceptTypeNo_Id=p.AcceptType_Id and  p.Id={0}";
                select_sql = string.Format(select_sql, productId);
                DataTable dt_typestyle = db.QueryTable(select_sql, 300);
                List<string> lststrs = new List<string>();
                if (dt_typestyle != null && dt_typestyle.Rows.Count == 1)
                {
                    if (dt_typestyle.Rows[0][0] != null && !string.IsNullOrEmpty(dt_typestyle.Rows[0][0].ToString().Trim()))
                    {
                        lststrs.Add(dt_typestyle.Rows[0][0].ToString().Trim());
                    }
                    if (dt_typestyle.Rows[0][1] != null && !string.IsNullOrEmpty(dt_typestyle.Rows[0][1].ToString().Trim()))
                    {
                        lststrs.Add(dt_typestyle.Rows[0][1].ToString().Trim());
                    }
                }
                if (lststrs.Count > 0)
                {
                    type_style_url = string.Join("/", lststrs.ToArray()) + "/";
                }
                relativeUrl = type_style_url + Utils.ToBase64(selectNo) + ".html";
            }
            catch (Exception ex)
            {
                LogUtils.LogError("老系统 二维码服务生成相对URL出错", Developer.MJ, ex, "样品序号:" + productId, "样品编号:" + selectNo);
            }
            return relativeUrl;
        }

        /// <summary>
        /// 根据样品序号 构建二维码 报告页面信息
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public static string BuildHtml(string productId)
        {
            DBSession db = new DBSession(DataBaseType.MsSql);
            StringBuilder sb = new StringBuilder();
            string html = GetQrCodeContent();
            string sql = "select top 1 样品编号 as 报告编号,委托单位,委托日期,接收时间 as 来样日期,样品名称,型号规格,厂家单位 as 生产单位,dbo.GetStandardText(参照标准,引用标准,检验依据) as 检验依据,dbo.GetTestItemText({0},检测项目)  as 检测项目,检测结论,报告时间 as 签发日期,检测资质 as 检测单位 from TestQEPReport11View  where 样品序号={0}";
            sql = string.Format(sql, productId);
            List<DataTable> lstTbs = db.Query(sql, 300);
            if (lstTbs != null && lstTbs.Count == 1 && lstTbs[0].Rows.Count == 1)
            {
                DataTable data = lstTbs[0];
                foreach (DataColumn dc in data.Columns)
                {
                    string columnName = dc.ColumnName;
                    string value = data.Rows[0][columnName].ToString();
                    DateTime time;
                    if (DateTime.TryParse(value, out time))
                    {
                        value = time.ToString("yyyy-MM-dd");
                    }
                    if (columnName == "检验依据" || columnName == "检测结论" || columnName == "检测项目")
                    {
                        if (!string.IsNullOrEmpty(value) && !string.IsNullOrEmpty(value.Trim()))
                        {
                            value = ReplaceSpecialChar(value);
                        }
                    }
                    sb.AppendLine("<tr><td class=\"td-header\">" + columnName + "</td><td  class=\"td-content\">" + value + "</td></tr>");
                }
            }
            string tr_html = sb.ToString() + GetCommonInfo();
            html = html.Replace("{content}", tr_html);
            return html;
        }

        /// <summary>
        /// 将报告中的特殊字符替换为图片地址
        /// </summary>
        /// <returns></returns>
        public static string ReplaceSpecialChar(string val)
        {
            if (string.IsNullOrEmpty(val))
            {
                return string.Empty;
            }
            DBSession db = new DBSession(DataBaseType.MsSql);
            string sql = "SELECT * FROM dbo.SpecialChar WHERE [Str] IN " + Utils.GetInSqlChar(val) + "";
            DataTable dt_special = db.QueryTable(sql, 300);
            if (dt_special != null && dt_special.Rows.Count > 0)
            {
                foreach (DataRow dr in dt_special.Rows)
                {
                    string special_str = dr["Str"].ToString();
                    string imgUrl = dr["ImgUrl"] != null ? dr["ImgUrl"].ToString() : string.Empty;
                    if (!string.IsNullOrEmpty(imgUrl))
                    {
                        string img = "<img src=\"" + imgUrl + "\"/>";
                        val = val.Replace(special_str, img);
                    }
                }
            }
            return val;
        }


        /// <summary>
        /// 获取二维码扫描跳转的url 页面模板
        /// </summary>
        /// <returns></returns>
        public static string GetQrCodeContent()
        {
            string htmlfile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Template\\QrCodeContent.html");
            if (File.Exists(htmlfile))
            {
                return File.ReadAllText(htmlfile, Encoding.UTF8);
            }
            return string.Empty;
        }


        /// <summary>
        /// 二维码公共信息
        /// </summary>
        /// <returns></returns>
        public static string GetCommonInfo()
        {
            string qr_website = ConfigurationManager.AppSettings["QR_Common_WebSite"];
            string qr_phone = ConfigurationManager.AppSettings["QR_Common_Phone"];
            string qr_fax = ConfigurationManager.AppSettings["QR_Common_Fax"];
            string qr_address = ConfigurationManager.AppSettings["QR_Common_Address"];

            StringBuilder sb = new StringBuilder();
            if (!string.IsNullOrEmpty(qr_website))
            {
                qr_website = string.Format("<a href='{0}'>{0}</a>", qr_website.Trim());
                sb.AppendLine("<tr><td class=\"td-header\">" + "网址" + "</td><td  class=\"td-content\">" + qr_website + "</td></tr>");
            }
            if (!string.IsNullOrEmpty(qr_phone))
            {
                sb.AppendLine("<tr><td class=\"td-header\">" + "客服电话" + "</td><td  class=\"td-content\">" + qr_phone.Trim() + "</td></tr>");
            }
            if (!string.IsNullOrEmpty(qr_fax))
            {
                sb.AppendLine("<tr><td class=\"td-header\">" + "传真" + "</td><td  class=\"td-content\">" + qr_fax.Trim() + "</td></tr>");
            }
            if (!string.IsNullOrEmpty(qr_address))
            {
                sb.AppendLine("<tr><td class=\"td-header\">" + "地址" + "</td><td  class=\"td-content\">" + qr_address.Trim() + "</td></tr>");
            }
            return sb.ToString();
        }

    }
}
